<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>

<script>
  const data = [
    { id: 2, pid: 1 },
    { id: 5, pid: 2 },
    { id: 3, pid: 1 },
    { id: 1, pid: 0 },
    { id: 4, pid: 2 },
    { id: 6, pid: 3 }
  ]

  const tranListToTreeData = (list, pid) => {
    let arr = []
    list.forEach(item => {
      if (item.pid === pid) {
        // 继续调用判断是否有下一级
        const children = tranListToTreeData(list, item.id)
        if (children.length) {
          item.children = children
        }
        arr.push(item)
      }
    })
    return arr
  }
  let res = tranListToTreeData(data, 0)
  console.log(res)
</script>
</body>
</html>
